<?php

class AuthController extends Zend_Controller_Action 
{
	function init() 
	{
		// Initialize the view
		$this->initView();
		// Store the base url for the current request in the view
		$this->view->baseUrl = $this->_request->getBaseUrl();	
	}
	
	function indexAction() 
	{	
		// Anyone requesting this controller will be redirected
		$this->_redirect('/');
	}
	
	function logoutAction()
	{
		Zend_Auth::getInstance()->clearIdentity();
		$this->_redirect('/');
	}
	
	function loginAction()
	{
		$this->view->message = '';
		
		if ($this->_request->isPost()) {
			
			// collect the data from the user
			Zend_Loader::loadClass('Zend_Filter_StripTags');
			$f = new Zend_Filter_StripTags();
			$username = $f->filter($this->_request->getPost('username'));
			$password = $f->filter($this->_request->getPost('password'));
			
			if (empty($username)) {
				$this->view->message = 'Please provide a username.';
			} else {
				// setup Zend_Auth adapter for a database table
				Zend_Loader::loadClass('Zend_Auth_Adapter_DbTable');
				$db = Zend_Registry::getInstance()->database;
				$authAdapter = new Zend_Auth_Adapter_DbTable($db);
				$authAdapter->setTableName('users');
				$authAdapter->setIdentityColumn('username');
				$authAdapter->setCredentialColumn('password');
				
				// Treat credentials as SHA1 hashes
				$authAdapter->setCredentialTreatment('SHA1(?)');
				
				// Set the input credential values to authenticate against
				$authAdapter->setIdentity($username);
				$authAdapter->setCredential($password);
				
				// do the authentication
				$auth = Zend_Auth::getInstance();
				$result = $auth->authenticate($authAdapter);
				
				if ($result->isValid()) {
					// success: store database row to auth's storage
					// system. (Not the password though!)
					$data = $authAdapter->getResultRowObject(null, 'password');
					$auth->getStorage()->write($data);
					$this->_redirect('/');
				} else {
					// failure: clear database row from session
					$this->view->message = 'Login failed.';
				}
			}
		}
		$this->view->title = "Log in";
	}
}